package com.c2rusthub.service.interceptor;

import com.c2rusthub.service.response.Response;
import com.c2rusthub.service.utils.UserCacheUtil;
import com.google.gson.Gson;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (1 == 1) {
//            跳过验证
            return true;
        }
        // 从请求头中获取 token（假设我们使用 token 来验证登录）
        String token = request.getHeader("Authorization");

        // 如果 token 为空，认为未登录
        if (token == null || token.isEmpty()) {
            // 设置响应状态为 401 未授权
            response.setContentType("application/json; charset=UTF-8");  // 设置内容类型及编码
            response.setCharacterEncoding("UTF-8");  // 设置响应字符编码为 UTF-8
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(new Gson().toJson(new Response(1, "未登录或无效的 token", null)));
            return false;
        }

        // 使用缓存来验证 token 是否存在
        if (UserCacheUtil.getUserFromCache(token) == null) {
            // 如果缓存中没有该 token，表示未登录
            response.setContentType("application/json; charset=UTF-8");  // 设置内容类型及编码
            response.setCharacterEncoding("UTF-8");  // 设置响应字符编码为 UTF-8
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(new Gson().toJson(new Response(1, "未登录或无效的 token", null)));
            return false;
        }

        // 如果缓存中存在 token，认为已登录
        return true;
    }
}
